$(document).ready(function () {
    
    //Local "constants"
    var SERVICE_URL = "/kiviq/searchprovider";
    var QUESTION_TITLE = "questionTitle";
    var ANSWER = "answer";
    var RESULT = "result";
    var MATCHED_WORDS = "matchedWords";
    var RETURN_KEY = 13;
    
    //The search text input
    var search = $("#search");
    //The result placeholder element
    var result = $("#results");
    
    //Set an error message using the
    //"error" element
    var errorMessage = function(message) {
	$("#error").text(message);
    };
    
    //Create a button that clears the results
    //when clicked
    var createClearButton = function() {
	var btn = document.createElement("input");
	btn.type = "button";
	btn.value = "Clear results";
	btn.className = "clearButton";
	$(btn).click(function() {
	    result.fadeOut(150, function() {
		result.html("");
		result.fadeIn(50);
	    });
	});
	return btn;
    };
    
    //Creates a div given text content and
    //a class name
    var createDiv = function(text, className) {
	var ret = document.createElement("div");
	$(ret).attr("class", className).text(text);
	return ret;
    };
    
    //Appends a result-div to the results and fades it in
    var addResult = function(title, answer, keywords) {
	var div = $(document.createElement("div"));
	div.attr("class", "result");
	
	div.append(createDiv(title, "resultTitle"));
	div.append(createDiv(answer, "resultAnswer"));
	div.append(createDiv(keywords, "resultKeywords"));
	
	div.fadeIn(250);
	result.append(div);
    };
    
    //Loads the XML response that was retreived
    //from the kiviq application search service
    var loadData = function(data) {
	result.html("");
	
	var areResults = false;
	$(data).find(RESULT).each(function() {
	    var $this = $(this);
	    var title = $this.attr(QUESTION_TITLE);
	    var answer = $this.attr(ANSWER);
	    var keywords = $this.attr(MATCHED_WORDS);
	    
	    addResult(title, answer, keywords);
	    areResults = true;
	});
	if (areResults) {
	    result.append(createClearButton());
	}
    };
    
    //Starts an AJAX search request
    var doSearch = function(keywords) {
	result.html("");
	var prog = IndeterminateProgress.show(result);
	$.ajax({
	    url: SERVICE_URL,
	    type: "POST",
	    dataType: "xml",
	    data: {
		"keywords": keywords
	    },
	    success: function(data) {
		prog.stop();
		loadData(data);
	    }
	});
    };
    
    //Initiates the search and prevents
    //the default event
    var initiateSearch = function(e) {
	var text = $.trim(search.val());
	if (text.length != 0) {
	    errorMessage("");
	    doSearch(text);
	} else {
	    errorMessage("Please enter search keywords");
	}
	e.preventDefault();
    };
    
    //Register a key listener to the search
    //textinput element, initiates a search
    //when the return key is pressed
    search.keypress(function(e) {
	if ((e.keyCode ? e.keyCode : e.which) == RETURN_KEY) {
	    initiateSearch();
	}
    });
    
});